/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.swe.chums.beans;

import com.swe.chums.dao.CommentDao;
import com.swe.chums.dao.CommentLikeDao;
import com.swe.chums.dao.CourseRelationDao;
import com.swe.chums.dao.LessonsDao;
import com.swe.chums.dao.RatingDao;
import com.swe.chums.dao.RatingTypeDao;
import com.swe.chums.dao.SourceDao;
import com.swe.chums.dao.TagDao;
import com.swe.chums.dao.TagTypeDao;
import com.swe.chums.dao.UserDao;
import com.swe.chums.dao.UserFavoriteDao;
import com.swe.chums.dao.WebResourceDao;
import com.swe.chums.dao.exceptions.CommentDaoException;
import com.swe.chums.dao.exceptions.CommentLikeDaoException;
import com.swe.chums.dao.exceptions.LessonsDaoException;
import com.swe.chums.dao.exceptions.RatingDaoException;
import com.swe.chums.dao.exceptions.RatingTypeDaoException;
import com.swe.chums.dao.exceptions.SourceDaoException;
import com.swe.chums.dao.exceptions.TagDaoException;
import com.swe.chums.dao.exceptions.TagTypeDaoException;
import com.swe.chums.dao.exceptions.UserDaoException;
import com.swe.chums.dao.exceptions.WebResourceDaoException;
import com.swe.chums.dao.factory.DaoFactory;
import com.swe.chums.dao.model.Comment;
import com.swe.chums.dao.model.CommentLike;
import com.swe.chums.dao.model.CommentLikePk;
import com.swe.chums.dao.model.CommentPk;
import com.swe.chums.dao.model.Lessons;
import com.swe.chums.dao.model.Rating;
import com.swe.chums.dao.model.RatingPk;
import com.swe.chums.dao.model.Source;
import com.swe.chums.dao.model.Tag;
import com.swe.chums.dao.model.TagType;
import com.swe.chums.dao.model.UserFavorite;
import com.swe.chums.dao.model.UserFavoritePk;
import com.swe.chums.dao.model.WebResource;
import com.swe.chums.dao.model.WebResourcePk;
import com.swe.chums.utils.CommonUtils;
import com.swe.chums.utils.UserActivityTypeEnum;
import com.swe.chums.utils.WebResourceTypeEnum;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.primefaces.event.RateEvent;
import org.primefaces.event.RowEditEvent;
import org.primefaces.model.DashboardColumn;
import org.primefaces.model.DashboardModel;
import org.primefaces.model.DefaultDashboardColumn;
import org.primefaces.model.DefaultDashboardModel;

/**
 *
 * @author cilingir
 */
@ManagedBean(name = "webResourceBean")
@ViewScoped
public class WebResourceBean implements Serializable {

    private static Logger log = Logger.getLogger(WebResourceBean.class);
    private boolean searchFinished;
    private String searchText, newCommentText, tagSuggestion;
    private Integer rate; 
    private Comment toBeRemovedComment;
    private ArrayList<Lessons> lessons = new ArrayList<Lessons>();
    private WebResource selectedResult;
    private ArrayList<WebResource> searchResults = new ArrayList<WebResource>();
    private ArrayList<Comment> commentList = new ArrayList<Comment>();
    private DashboardModel topsDashboard, rightCoursesPanel, rightAdminPanel;
    private ArrayList<WebResource> lastCourses, lastInstitutions, topCourses, topInstitutions, topInstructors, trendingCourses;
    private ArrayList<Lessons> lessonResults = new ArrayList<Lessons>();
    public WebResourceBean() {
        lastCourses = getLastWebResources(5, WebResourceTypeEnum.COURSE.getId());
        lastInstitutions = getLastWebResources(5, WebResourceTypeEnum.INSTITUTION.getId());
        topCourses = getTopWebResources(5, WebResourceTypeEnum.COURSE.getId());
        topInstitutions = getTopWebResources(5, WebResourceTypeEnum.INSTITUTION.getId());
        topInstructors = getTopWebResources(5, WebResourceTypeEnum.INSTRUCTOR.getId());
        trendingCourses = getTrendingWebResources(5, WebResourceTypeEnum.COURSE.getId());
    }

    /**
     * Search operation
     * 
     */
    public void search() {
        String searchField = null;

        searchResults.clear();
        
        if (searchText.contains(" (")) {
            searchField = searchText.substring(searchText.indexOf(" (") +2, searchText.length()-1);
            searchText = searchText.substring(0, searchText.indexOf(" ("));
        }
        
        ArrayList<WebResource> resultList = retrieveCoursesFromExternalResources(searchText);
        if (!resultList.isEmpty()) {
            searchResults.addAll(resultList);
        }
        
        lessonResults.clear();
        lessonResults = retrieveLessons(searchText);
        // Treat lessons as webresource to let them have comments and rating etc.
//        try {
//            WebResourceDao wDao = DaoFactory.createWebResourceDao();
//            for (int i=0; i<lessonResults.size(); i++) {
//                Lessons currentLesson = lessonResults.get(i);
//                if (wDao.findWhereTitleEquals(currentLesson.getTitle()).size()<=0) {
//                    WebResource wr = new WebResource();
//                    wr.setTitle(currentLesson.getTitle());
//                    if (currentLesson.getUrl() != null && !currentLesson.getUrl().isEmpty()) {
//                        wr.setUrl(currentLesson.getUrl());
//                    }
//                    wDao.insert(wr);
//                    searchResults.add(wr)
//                }
//            }
//        } catch (Exception ex) {
//            log.error("Lesson error");
//        }

        LoginBean loginBean = (LoginBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("loginBean");
        if (loginBean != null && loginBean.isLoggedIn()) {
            CommonUtils.recordUserAction(loginBean.getUser().getId(), UserActivityTypeEnum.SEARCH, 0, searchText);
        }

        searchFinished = true;
    }
    
    /**
     * Add to favorite
     * 
     */
    public void addToFavorite() {
        FacesContext context = FacesContext.getCurrentInstance();
        LoginBean loginBean = (LoginBean) context.getExternalContext().getSessionMap().get("loginBean");
        UserFavoriteDao ufDao = DaoFactory.createUserFavoriteDao();
        
        if (loginBean!=null && loginBean.isLoggedIn()) {
            int currentUserID = ((LoginBean) context.getExternalContext().getSessionMap().get("loginBean")).getUser().getId();
            try {
                UserFavorite uf = new UserFavorite();
                uf.setUserId(currentUserID);
                uf.setWebResourceId(selectedResult.getId());
                ufDao.insert(uf);
                
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Course favorited"));
                selectedResult.setFavorited(true);
                CommonUtils.recordUserAction(currentUserID, UserActivityTypeEnum.FAVORITE, selectedResult.getId(), null);
            } catch (Exception ex) {
                log.error("error: " + ex.getMessage());
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "INFO", "Error"));
            }
        }
    }
    
    /**
     * Remove from favorite
     * 
     */
    public void removeFromFavorite() {
        FacesContext context = FacesContext.getCurrentInstance();
        LoginBean loginBean = (LoginBean) context.getExternalContext().getSessionMap().get("loginBean");
        UserFavoriteDao ufDao = DaoFactory.createUserFavoriteDao();
        
        if (loginBean!=null && loginBean.isLoggedIn()) {
            int currentUserID = ((LoginBean) context.getExternalContext().getSessionMap().get("loginBean")).getUser().getId();
            try {
                UserFavorite uf = new UserFavorite();
                uf.setUserId(currentUserID);
                uf.setWebResourceId(selectedResult.getId());
                ArrayList<UserFavorite> ufList = (ArrayList<UserFavorite>) ufDao.findWhereUserIdAndWebResourceIdEquals(currentUserID, selectedResult.getId());
                if (ufList.size()>0) {
                    UserFavoritePk ufpk = new UserFavoritePk(ufList.get(0).getId());
                    ufDao.delete(ufpk);
                    selectedResult.setFavorited(false);
                    context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Course removed from favorites"));
                }
                
            } catch (Exception ex) {
                log.error("erro: " + ex.getMessage());
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "ERROR"));
            }
            
        }
    }
    
    /**
     * Add tag
     * 
     * @throws TagDaoException 
     */
    public void addTag() throws TagDaoException {
        log.debug("[WebResourceBean.addTag] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        String errorText = "HATA";
        WebResourceDao wrDao = DaoFactory.createWebResourceDao();
        TagDao tDao = DaoFactory.createTagDao();
        TagTypeDao ttDao = DaoFactory.createTagTypeDao();
        
        if (tagSuggestion!=null && !tagSuggestion.equals("")) {
            try {
                if (selectedResult != null) {
                    if (selectedResult.getId()<=0) {
                        WebResource w = wrDao.findWhereUrlEquals(selectedResult.getUrl()).get(0);
                        selectedResult.setId(w.getId());
                    }    
                    TagType tt = new TagType(); 
                    ArrayList<TagType> tts = (ArrayList<TagType>) ttDao.findWhereNameEquals(tagSuggestion);
                    if (tts.size()>0) {
                        tt = tts.get(0);
                    } else {
                        tt.setName(tagSuggestion);
                        ttDao.insert(tt);
                        tt.setId(ttDao.findWhereNameEquals(tagSuggestion).get(0).getId());
                    }
                    
                    ArrayList<Tag> wTags = (ArrayList<Tag>) tDao.findWhereWebResourceIdEquals(selectedResult.getId());
                    String tags = "";
                    boolean tagFound = false;
                    for (int i=0; i<wTags.size(); i++) {
                        if (wTags.get(i).getTagTypeId() == tt.getId()) {
                            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "Tag already exists!"));
                            tagFound = true;
                        }
                        tags += ttDao.findWhereIdEquals(wTags.get(i).getTagTypeId()).get(0).getName() + " ";
                    }
                    
                    if (!tagFound) {
                        Tag t = new Tag();
                        t.setWebResourceId(selectedResult.getId());
                        t.setTagTypeId(tt.getId());
                        tDao.insert(t);
                        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, errorText, "Tag added"));
                        tags += tagSuggestion; 
                    }
                    selectedResult.setTagsText(tags);
                    LoginBean loginBean = (LoginBean) context.getExternalContext().getSessionMap().get("loginBean");
                    if (loginBean!=null && loginBean.isLoggedIn()) {
                        int currentUserID = ((LoginBean) context.getExternalContext().getSessionMap().get("loginBean")).getUser().getId();
                        CommonUtils.recordUserAction(currentUserID, UserActivityTypeEnum.TAG, selectedResult.getId(), tagSuggestion);
                    }
                    
                    
                    tagSuggestion = "";
                }
                
            } catch (WebResourceDaoException ex) {
                log.error("[WebResourceBean.addTag] - error while retrieving values from DB, message is:  " + ex.getMessage());
            } catch (TagTypeDaoException ex) {
                log.error("[WebResourceBean.addTag] - error while retrieving values from DB, message is:  " + ex.getMessage());
            } catch (TagDaoException ex) {
                log.error("[WebResourceBean.addTag] - error while retrieving values from DB, message is:  " + ex.getMessage());
            }
        } else {
            tagSuggestion = "";
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "You must enter a value to tag it!"));
        }
    }
    
    /**
     * Retrieve courses from external sources
     * 
     * @param searchText
     * @return 
     */
    public ArrayList<WebResource> retrieveCoursesFromExternalResources(String searchText) {
        
        ArrayList<WebResource> resultList = new ArrayList<WebResource>();
        ArrayList<Source> externalSources = new ArrayList<Source>();
        
        CourseRelationDao crDao = DaoFactory.createCourseRelationDao();
        WebResourceDao wrDao = DaoFactory.createWebResourceDao();
        TagDao tDao = DaoFactory.createTagDao();
        TagTypeDao ttDao = DaoFactory.createTagTypeDao();
        SourceDao sDao = DaoFactory.createSourceDao();
        RatingDao rDao = DaoFactory.createRatingDao();
        try {
            externalSources = (ArrayList<Source>) sDao.findAll();
            
            searchText = CommonUtils.reconstructSearchText(searchText);
            
            for(Source currentSource : externalSources ){
                
                 if (currentSource.getName().startsWith("https://www.udemy")) {
                    
                    String currentSourceURL = currentSource.getName().replace("KEY+WORD", searchText);
                     
                    try {
                        Document doc = Jsoup.connect(currentSourceURL).timeout(20*1000).userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
      .referrer("http://www.google.com")
      .get();
                    
                    //Document doc = Jsoup.connect(currentSourceURL).get();
                        
                        Elements courseLis = doc.select("li.course-item-list");
                        
                        if (!courseLis.isEmpty()) {
                            int max = courseLis.size()>2 ? 2 : courseLis.size();
                            for (int i=0; i<max; i++) {
                                
                                String title = courseLis.get(i).select("span.title.ellipsis").first().text();
                                String url = courseLis.get(i).select("a").attr("href");
                                String desc = courseLis.get(i).select("div.desc.ellipsis").first().text();
                                
                                String instructor = courseLis.get(i).select("span.ins.ellipsis").first().text();
                                String institution = "Udemy";
                                
                                WebResource wr = new WebResource();
                                wr.setWebResourceTypeId(WebResourceTypeEnum.COURSE.getId());
                                wr.setDescription(desc);
                                wr.setTitle(title);
                                wr.setUrl(url);
                                wr.setTagsText("");
                                wr.setInstructorsText(instructor);
                                wr.setInsertDate(new Date());
                                wr.setInstitutionText(institution);
                                wr.setAverageRating(0.0);
                                wr.setHitCount(1);

                                boolean newInsert = false;
                                if (wrDao.findWhereUrlEquals(wr.getUrl()).isEmpty()) {
                                    WebResourcePk pk = wrDao.insert(wr);
                                    wr.setId(pk.getId());
                                    newInsert = true;
                                } else {
                                    WebResource w = wrDao.findWhereUrlEquals(wr.getUrl()).get(0);
                                    wr.setId(w.getId());
                                    wr.setAverageRating(w.getAverageRating());
                                    int averageRatingInt = w.getAverageRating().intValue();
                                    wr.setAverageRatingInt(averageRatingInt);
                                    wr.setInsertDate(w.getInsertDate());
                                    wr.setRatingCount(rDao.findWhereWebResourceIdEquals(wr.getId()).size());
                                    ArrayList<Tag> wTags = (ArrayList<Tag>) tDao.findWhereWebResourceIdEquals(wr.getId());
                                    String tags = "";
                                    for (int k=0; k<wTags.size(); k++) {
                                        tags += ttDao.findWhereIdEquals(wTags.get(k).getTagTypeId()).get(0).getName() + " ";
                                    }
                                    wr.setTagsText(tags);
                                    wr.setFavorited(getIfUserFavoritedCourse(wr.getId()));
                                    
                                    w.setHitCount(w.getHitCount()+1);
                                    wrDao.update(new WebResourcePk(w.getId()), w);
                                }
                                
                                if (newInsert) {
                                    // Add lessons
                                    //Document coursePage= Jsoup.connect(url).get();
                                    Document coursePage = Jsoup.connect(url).timeout(20*1000).userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6").get();

                                    lessons = new ArrayList<Lessons>();
                                    Elements lessonLis = coursePage.select("li.single-lecture");
                                    for (int k=0; k<lessonLis.size(); k++) {
                                        try {
                                        String lessonUrl = lessonLis.get(k).select("a").first().attr("href");
                                        String lessonTitle = lessonLis.get(k).select("div.details a").text();

                                        Lessons l = new Lessons();
                                        l.setTitle(lessonTitle);
                                        l.setUrl(lessonUrl);
                                        l.setWebresourceId(wr.getId());
                                        
                                        DaoFactory.createLessonsDao().insert(l);
                                        lessons.add(l);
                                        } catch (Exception ex) {
                                            log.error("error: " + ex.getMessage());
                                        }
                                    } 
                                } else {
                                    lessons = (ArrayList<Lessons>) DaoFactory.createLessonsDao().findWhereWebresourceIdEquals(wr.getId());
                                }
                                wr.setLessons(lessons);
                                resultList.add(wr);
                            }
                        }
                    }catch (Exception ex) {
                        log.error("error: " + ex.getMessage());
                    }
                } else if (currentSource.getName().startsWith("http://coursetalk.org/")) {
                
                    String currentSourceURL = currentSource.getName().replace("KEY+WORD", searchText);
                    
                    try {
                        Document doc = Jsoup.connect(currentSourceURL).timeout(20*1000).get();
                        Elements courses = doc.select("table.course_list tr");
                        for (int i = 1; i < courses.size(); i++) {
                             try {
                                Elements courseColumns = courses.get(i).select("td");
                                String institution = courseColumns.first().select("a").attr("href");
                                Elements courseColumns2 = courseColumns.get(1).select("a");
                                String extractorPath = "http://coursetalk.org" + courseColumns2.get(0).attr("href");
                                String title = courseColumns2.first().html();
                                String university = "";
                                String instructor = "";
                                if (courseColumns2.size() > 1) {
                                    university = courseColumns2.get(1).html();
                                    String[] instructorInstitution = courseColumns.get(1).text().split("Ñ");
                                    if (instructorInstitution.length > 1) {
                                        instructor = instructorInstitution[1].trim();
                                    }
                                } else {
                                    instructor = courseColumns.get(1).text().substring(title.length() + 1);
                                }
                                String[] ratingVal = courseColumns.get(2).select("div.stars").attr("class").split(" ");
                                String rating = "";
                                if (ratingVal.length > 1) {
                                    rating = ratingVal[1].substring(1);
                                }

                                Document coursePage= Jsoup.connect(extractorPath).get();
                                String courseCustomUrl = coursePage.select("div.course_box a").first().attr("href");

                                String descSource = coursePage.select("iframe").first().attr("src");
                                Document descDetails = Jsoup.connect("http://coursetalk.org" + descSource).get();
                                String desc = descDetails.select("body").first().html();
                                int start = courseCustomUrl.indexOf("http");
                                String url = courseCustomUrl.substring(start);

                                WebResource wr = new WebResource();

                                wr.setWebResourceTypeId(WebResourceTypeEnum.COURSE.getId());
                                wr.setDescription(desc);
                                wr.setTitle(title);
                                wr.setUrl(url);
                                wr.setTagsText("");
                                wr.setInstructorsText(instructor);
                                wr.setInsertDate(new Date());
                                wr.setInstitutionText(institution);
                                wr.setAverageRating(0.0);
                                wr.setHitCount(1);

                                boolean newInsert=false;
                                if (wrDao.findWhereUrlEquals(wr.getUrl()).isEmpty()) {
                                    WebResourcePk pk = wrDao.insert(wr);
                                    wr.setId(pk.getId());
                                    newInsert=true;
                                } else {
                                    WebResource w = wrDao.findWhereUrlEquals(wr.getUrl()).get(0);
                                    wr.setId(w.getId());
                                    wr.setAverageRating(w.getAverageRating());
                                    int averageRatingInt = w.getAverageRating().intValue();
                                    wr.setAverageRatingInt(averageRatingInt);
                                    wr.setInsertDate(w.getInsertDate());
                                    wr.setRatingCount(rDao.findWhereWebResourceIdEquals(wr.getId()).size());
                                    ArrayList<Tag> wTags = (ArrayList<Tag>) tDao.findWhereWebResourceIdEquals(wr.getId());
                                    String tags = "";
                                    for (int k=0; k<wTags.size(); k++) {
                                        tags += ttDao.findWhereIdEquals(wTags.get(k).getTagTypeId()).get(0).getName() + " ";
                                    }
                                    wr.setTagsText(tags);
                                    wr.setFavorited(getIfUserFavoritedCourse(wr.getId()));
                                    
                                    w.setHitCount(w.getHitCount()+1);
                                    wrDao.update(new WebResourcePk(w.getId()), w);
                                }

                                if (newInsert){
                                    if (institution.contains("/udacity")) {
                                        Document courseCustomPage= Jsoup.connect(url).timeout(20*1000).get();
                                        lessons = new ArrayList<Lessons>();
                                        Elements lessonLis = courseCustomPage.select("div.syllabus h3");
                                        for (int k=0; k<lessonLis.size(); k++) {
                                            try {
                                            String lessonUrl = "";
                                            String lessonTitle = lessonLis.get(k).text();

                                            Lessons l = new Lessons();
                                            l.setTitle(lessonTitle);
                                            l.setUrl(lessonUrl);
                                            l.setWebresourceId(wr.getId());

                                            DaoFactory.createLessonsDao().insert(l);
                                            lessons.add(l);
                                            } catch (Exception ex) {
                                                log.error("error: " + ex.getMessage());
                                            }
                                        }
                                    } else if (institution.contains("/open2study")) {
                                        Document courseCustomPage= Jsoup.connect(url).timeout(20*1000).get();
                                        lessons = new ArrayList<Lessons>();
                                        Elements lessonLis = courseCustomPage.select("table.whats-involved tr");
                                        for (int k=0; k<lessonLis.size(); k++) {
                                            try {
                                            String lessonUrl = "";
                                            String lessonTitle = lessonLis.get(k).select("td").first().select("span.title").text();

                                            Lessons l = new Lessons();
                                            l.setTitle(lessonTitle);
                                            l.setUrl(lessonUrl);
                                            l.setWebresourceId(wr.getId());

                                            DaoFactory.createLessonsDao().insert(l);
                                            lessons.add(l);
                                            } catch (Exception ex) {
                                                log.error("error: " + ex.getMessage());
                                            }
                                        }
                                    } else if (institution.contains("/codeschool")) {
                                        Document courseCustomPage= Jsoup.connect(url).timeout(20*1000).get();
                                        lessons = new ArrayList<Lessons>();
                                        Elements lessonLis = courseCustomPage.select("div.overview div.card-a.level");
                                        for (int k=0; k<lessonLis.size(); k++) {
                                            try {
                                            String lessonUrl = "";
                                            String lessonTitle = lessonLis.get(k).select("h4.h3.level-name").first().text();

                                            Lessons l = new Lessons();
                                            l.setTitle(lessonTitle);
                                            l.setUrl(lessonUrl);
                                            l.setWebresourceId(wr.getId());

                                            DaoFactory.createLessonsDao().insert(l);
                                            lessons.add(l);
                                            } catch (Exception ex) {
                                                log.error("error: " + ex.getMessage());
                                            }
                                        }
                                    }
                                } else {
                                    lessons = (ArrayList<Lessons>) DaoFactory.createLessonsDao().findWhereWebresourceIdEquals(wr.getId());
                                }
                                
                                wr.setLessons(lessons);
                                
                                resultList.add(wr);

                             } catch (Exception e) {

                             }
                        }
                    } catch (Exception e) {

                    }
                } else if (currentSource.getName().startsWith("https://www.khanacademy")) {
                    String currentSourceURL = currentSource.getName().replace("KEY+WORD", searchText);
                    
                    try {
                        Document doc = Jsoup.connect(currentSourceURL).timeout(20*1000).get();
                        Elements courseCustomUrl = doc.select("section.topics");
                        Elements topicADivs = courseCustomUrl.first().select("div.search-result-info a");
                        for (int i=0; i<topicADivs.size(); i++) {

                            String topic = topicADivs.get(i).select("span.searchresulthighlight").html();
                            String url = "https://www.khanacademy.org" + topicADivs.get(i).attr("href");
                            Document coursePage= Jsoup.connect(url).get();
                            Elements descEls = coursePage.select("span.long-description"); 
                            String desc = "";
                            if (!descEls.isEmpty()) {
                                desc = descEls.first().html();
                            } else {
                                descEls = coursePage.select("div.topic-desc");
                                if (!descEls.isEmpty()) {
                                    desc = descEls.first().html();
                                }
                            }

                            WebResource wr = new WebResource();
                            wr.setWebResourceTypeId(WebResourceTypeEnum.COURSE.getId());
                            wr.setDescription(desc);
                            wr.setTitle(topic);
                            wr.setUrl(url);
                            wr.setTagsText("");
                            wr.setInstructorsText("");
                            wr.setInsertDate(new Date());
                            wr.setInstitutionText("khanacademy");
                            wr.setAverageRating(0.0);
                            wr.setHitCount(1);
                            
                            if (wrDao.findWhereUrlEquals(wr.getUrl()).isEmpty()) {
                                wrDao.insert(wr);
                            } else {
                                WebResource w = wrDao.findWhereUrlEquals(wr.getUrl()).get(0);
                                wr.setId(w.getId());
                                int averageRatingInt = w.getAverageRating().intValue();
                                wr.setAverageRatingInt(averageRatingInt);
                                wr.setAverageRating(w.getAverageRating());
                                wr.setInsertDate(w.getInsertDate());
                                wr.setRatingCount(rDao.findWhereWebResourceIdEquals(wr.getId()).size());
                                ArrayList<Tag> wTags = (ArrayList<Tag>) tDao.findWhereWebResourceIdEquals(wr.getId());
                                wr.setFavorited(getIfUserFavoritedCourse(wr.getId()));
                                
                                String tags = "";
                                for (int k=0; k<wTags.size(); k++) {
                                    tags += ttDao.findWhereIdEquals(wTags.get(k).getTagTypeId()).get(0).getName() + " ";
                                }
                                wr.setTagsText(tags);
                                    
                                w.setHitCount(w.getHitCount()+1);
                                wrDao.update(new WebResourcePk(w.getId()), w);
                            }

                            resultList.add(wr);
                        }
                    } catch ( Exception ex) {
                        
                        
                    }
//                } else if (currentSource.getName().startsWith("https://www.coursera")) { // sonuçlar sonradan yüklendiği için sorunlu ama boşver nasılsa coursetalk buradan da çekiyor
//                    String currentSourceURL = currentSource.getName().replace("KEY+WORD", searchText);
//                    Document doc = Jsoup.connect(currentSourceURL).get();
//                    Elements courseListDivs = doc.select("div.coursera-catalog-listing-primary");
//                    for (int i=0; i<courseListDivs.size(); i++) {
//                        String university = courseListDivs.get(i).select("h4.coursera-catalog-listing-university").first().select("a").text();
//                        
//                        String title = courseListDivs.get(i).select("h3.coursera-catalog-listing-coursename").first().select("a").text();
//                        
//                        String instructor = courseListDivs.get(i).select("h4.coursera-catalog-listing-instructor").first().select("a").text();
//                        
//                        String url = "https://www.coursera.org/" + courseListDivs.get(i).select("h3.coursera-catalog-listing-coursename").first().select("a").first().attr("href");
//                        
//                        Document coursePage= Jsoup.connect(url).get();
//                        String desc = coursePage.select("div.span7 div.coursera-course-detail p").first().text(); 
//                        
//                    }
//                }
                } else if (currentSource.getName().startsWith("http://search.mit.edu")) {
                    
                    String currentSourceURL = currentSource.getName().replace("KEY+WORD", searchText);
                    
                    try {
                        Document doc = Jsoup.connect(currentSourceURL).timeout(20*1000).get();
                        Elements coursePs = doc.select("div.results_search > p:not(.helper)");
                        if (!coursePs.isEmpty()) {
                            for (int i=1; i<coursePs.size(); i++) {
                                String desc = coursePs.get(i).select("span.snippet").first().text();
                                String title = coursePs.get(i).select("a").first().text();
                                String url =  coursePs.get(i).select("a").attr("href");

                                Document coursePage= Jsoup.connect(url).get();

                                String instructor = coursePage.select("div#course_info p.ins").first().text(); 
                                String institution = "MIT";

                                WebResource wr = new WebResource();
                                wr.setWebResourceTypeId(WebResourceTypeEnum.COURSE.getId());
                                wr.setDescription(desc);
                                wr.setTitle(title);
                                wr.setUrl(url);
                                wr.setTagsText("");
                                wr.setInstructorsText(instructor);
                                wr.setInsertDate(new Date());
                                wr.setInstitutionText(institution);
                                wr.setAverageRating(0.0);
                                wr.setHitCount(1);

                                if (wrDao.findWhereUrlEquals(wr.getUrl()).isEmpty()) {
                                    wrDao.insert(wr);
                                } else {
                                    WebResource w = wrDao.findWhereUrlEquals(wr.getUrl()).get(0);
                                    wr.setId(w.getId());
                                    wr.setAverageRating(w.getAverageRating());
                                    int averageRatingInt = w.getAverageRating().intValue();
                                    wr.setAverageRatingInt(averageRatingInt);
                                    wr.setInsertDate(w.getInsertDate());
                                    wr.setRatingCount(rDao.findWhereWebResourceIdEquals(wr.getId()).size());
                                    ArrayList<Tag> wTags = (ArrayList<Tag>) tDao.findWhereWebResourceIdEquals(wr.getId());
                                    String tags = "";
                                    for (int k=0; k<wTags.size(); k++) {
                                        tags += ttDao.findWhereIdEquals(wTags.get(k).getTagTypeId()).get(0).getName() + " ";
                                    }
                                    wr.setTagsText(tags);
                                    wr.setFavorited(getIfUserFavoritedCourse(wr.getId()));
                                    w.setHitCount(w.getHitCount()+1);
                                    wrDao.update(new WebResourcePk(w.getId()), w);
                                }

                                resultList.add(wr);

                            }
                        }
                    }catch (Exception ex) {
                                
                    }
//                } else if (currentSource.getName().startsWith("http://www.google.com/cse?cx=partner-pub-3252929032242305")) {
//                    String currentSourceURL = currentSource.getName().replace("KEY+WORD", searchText);
//                    Document doc = Jsoup.connect(currentSourceURL).get();
//                    try {
//                        //Elements coursePs = doc.select("div.gsc-webResult.gsc-result");
//                        Elements courseTables = doc.select("table.gsc-table-result");
//                        for (int i=0; i<courseTables.size(); i++) {
//                            
//                            String url = courseTables.get(i).select("a.gs-title").attr("href");
//                            if (url.contains("http://www.mooc-list.com/course")) {
//                                String title = courseTables.get(i).select("a.gs-title").first().text();
//                                Document coursePage= Jsoup.connect(url).get();
//                                try {
//                                    String institution = coursePage.select("div.field-name-field-university-entity").first().select("a").first().text(); 
//                                    String instructor = coursePage.select("div.field-name-field-instructors").first().select("a").first().text(); 
//                                    String tags = coursePage.select("div.field-name-field-categories").first().select("a").first().text(); 
//                                    String desc = coursePage.select("div.field-type-text-with-summary").first().select("div.field-item.odd").first().text(); 
//                                                                        
//                                    WebResource wr = new WebResource();
//                                    wr.setWebResourceTypeId(WebResourceTypeEnum.COURSE.getId());
//                                    wr.setDescription(desc);
//                                    wr.setTitle(title);
//                                    wr.setUrl(url);
//                                    wr.setTagsText(tags);
//                                    wr.setInstructorsText(instructor);
//                                    wr.setInsertDate(new Date());
//                                    wr.setInstitutionText(institution);
//                                    wr.setAverageRating(0.0);
//
//                                    if (wrDao.findWhereUrlEquals(wr.getUrl().split("//")[1]).isEmpty()) {
//                                        wrDao.insert(wr);
//                                    }
//
//                                    resultList.add(wr);
//                                    
//                                    
//                                } catch (Exception ex) {
//                                    
//                                }
//                            }
//                            
//                        }
//                        
//                        
//                    }catch (Exception ex) {
//                                
//                    }
//                }
//                } else if (currentSource.getName().startsWith("http://www.saylor.org")) {
//                    String currentSourceURL = currentSource.getName().replace("KEY+WORD", searchText);
//                    Document doc = Jsoup.connect(currentSourceURL).get();
//                    try {
//                        //Elements coursePs = doc.select("div.gsc-webResult.gsc-result");
//                        Elements courseTables = doc.select("table.gsc-table-result");
//                        for (int i=0; i<courseTables.size(); i++) {
//                            
//                            String url = courseTables.get(i).select("div.gs-bidi-start-align.gs-visibleUrl.gs-visibleUrl-long").text();
//                            if (url.contains("www.saylor.org/courses")) {
//                                String title = courseTables.get(i).select("a.gs-title").first().text();
//                                Document coursePage= Jsoup.connect(url).get();
//                                try {
//                                    String institution = "saylor.org"; 
//                                    String instructor = coursePage.select("strong:containsOwn(Course Designer)").parents().first().text(); 
//                                    String desc = coursePage.select("div#purposeofcoursediv").first().text(); 
//                                                                        
//                                    WebResource wr = new WebResource();
//                                    wr.setWebResourceTypeId(WebResourceTypeEnum.COURSE.getId());
//                                    wr.setDescription(desc);
//                                    wr.setTitle(title);
//                                    wr.setUrl(url);
//                                    wr.setTagsText("");
//                                    wr.setInstructorsText(instructor);
//                                    wr.setInsertDate(new Date());
//                                    wr.setInstitutionText(institution);
//                                    wr.setAverageRating(0.0);
//
//                                    if (wrDao.findWhereUrlEquals(wr.getUrl().split("//")[1]).isEmpty()) {
//                                        wrDao.insert(wr);
//                                    }
//
//                                    resultList.add(wr);
//                                    
//                                    
//                                } catch (Exception ex) {
//                                    
//                                }
//                            }
//                            
//                        }
//                        
//                        
//                    }catch (Exception ex) {
//                                
//                    }

                } else if (currentSource.getName().startsWith("http://search.open.ac.uk")) {
                
                    String currentSourceURL = currentSource.getName().replace("KEY+WORD", searchText);
                    
                    try {
                        Document doc = Jsoup.connect(currentSourceURL).timeout(20*1000).get();
                        Elements courseLis = doc.select("li.hit.hitWithIcon");
                        if (!courseLis.isEmpty()) {
                            
                            for (int i=0; i<courseLis.size(); i++) {
                                
                                String title = courseLis.get(i).select("div.hitContent a").first().text();
                                String url = courseLis.get(i).select("div.hitContent a").attr("href");
                                String desc = courseLis.get(i).select("div.hitContent ul.metas li").first().text();
                                
                                String instructor = ""; 
                                String institution = "Openlearn";

                                WebResource wr = new WebResource();
                                wr.setWebResourceTypeId(WebResourceTypeEnum.COURSE.getId());
                                wr.setDescription(desc);
                                wr.setTitle(title);
                                wr.setUrl(url);
                                wr.setTagsText("");
                                wr.setInstructorsText(instructor);
                                wr.setInsertDate(new Date());
                                wr.setInstitutionText(institution);
                                wr.setAverageRating(0.0);
                                wr.setHitCount(1);

                                if (wrDao.findWhereUrlEquals(wr.getUrl()).isEmpty()) {
                                    wrDao.insert(wr);
                                } else {
                                    WebResource w = wrDao.findWhereUrlEquals(wr.getUrl()).get(0);
                                    wr.setId(w.getId());
                                    wr.setAverageRating(w.getAverageRating());
                                    int averageRatingInt = w.getAverageRating().intValue();
                                    wr.setAverageRatingInt(averageRatingInt);
                                    wr.setInsertDate(w.getInsertDate());
                                    wr.setRatingCount(rDao.findWhereWebResourceIdEquals(wr.getId()).size());
                                    ArrayList<Tag> wTags = (ArrayList<Tag>) tDao.findWhereWebResourceIdEquals(wr.getId());
                                    String tags = "";
                                    for (int k=0; k<wTags.size(); k++) {
                                        tags += ttDao.findWhereIdEquals(wTags.get(k).getTagTypeId()).get(0).getName() + " ";
                                    }
                                    wr.setTagsText(tags);
                                    wr.setFavorited(getIfUserFavoritedCourse(wr.getId()));
                                    w.setHitCount(w.getHitCount()+1);
                                    wrDao.update(new WebResourcePk(w.getId()), w);
                                }
                                resultList.add(wr);
                            }
                        }
                    }catch (Exception ex) {
                                
                    }
                        
                }
                
            }
            
        } catch (SourceDaoException ex) {
            log.error("error: " + ex.getMessage());
        } catch (Exception ex) {
            log.error("error: " + ex.getMessage());
        }
        
        return resultList;
    }

    /**
     * Get last webresources
     * 
     * @param size
     * @param webResourceTypeID
     * @return 
     */
    public ArrayList<WebResource> getLastWebResources(int size, int webResourceTypeID) {
        log.debug("[WebResourceBean.getLastWebResources] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        String errorText = "HATA";
        ArrayList<WebResource> lastWebResources = new ArrayList<WebResource>();
        try {
            lastWebResources = (ArrayList<WebResource>) DaoFactory.createWebResourceDao().findLatest(size, webResourceTypeID);
        } catch (WebResourceDaoException ex) {
            log.error("[WebResourceBean.getLastWebResources] - error while retrieving values from DB, message is:  " + ex.getMessage());
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        }
        return lastWebResources;
    }

    /**
     * Get top webresources
     * 
     * @param size
     * @param webResourceTypeID
     * @return 
     */
    public ArrayList<WebResource> getTopWebResources(int size, int webResourceTypeID) {
        log.debug("[WebResourceBean.getTopWebResources] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        String errorText = "HATA";
        ArrayList<WebResource> topWebResources = new ArrayList<WebResource>();
        try {
            topWebResources = (ArrayList<WebResource>) DaoFactory.createWebResourceDao().findTop(size, webResourceTypeID);
        } catch (WebResourceDaoException ex) {
            log.error("[WebResourceBean.getTopWebResources] - error while retrieving values from DB, message is:  " + ex.getMessage());
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        }
        return topWebResources;
    }
    
    /**
     * Get trending webresources
     * 
     * @param size
     * @param webResourceTypeID
     * @return 
     */
    public ArrayList<WebResource> getTrendingWebResources(int size, int webResourceTypeID) {
        log.debug("[WebResourceBean.getTrendingWebResources] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        ResourceBundle bundle = ResourceBundle.getBundle("resources.i18n.MessageResources", context.getViewRoot().getLocale());
        String errorText = "HATA";
        ArrayList<WebResource> trendingCourses = new ArrayList<WebResource>();
        try {
            trendingCourses = (ArrayList<WebResource>) DaoFactory.createWebResourceDao().getTrendingWebResources(size, webResourceTypeID);
        } catch (WebResourceDaoException ex) {
            log.error("[WebResourceBean.getTrendingWebResources] - error while retrieving values from DB, message is:  " + ex.getMessage());
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        }
        return trendingCourses;
    }
    
    /**
     * On rate event
     * 
     * @param rateEvent 
     */
    public void onRate(RateEvent rateEvent) {  
        
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        RatingDao rdao = DaoFactory.createRatingDao();
        RatingTypeDao rtdao = DaoFactory.createRatingTypeDao();
        
        WebResourceDao wrdao = DaoFactory.createWebResourceDao();
        
        String errorText = "ERROR";
        String rateExplained = "";
        
        LoginBean loginBean = (LoginBean) context.getExternalContext().getSessionMap().get("loginBean");
        if (loginBean!=null && loginBean.isLoggedIn()) {
            int currentUserID = ((LoginBean) context.getExternalContext().getSessionMap().get("loginBean")).getUser().getId();
            rate = ((Integer) rateEvent.getRating()).intValue();
            try {
                try {
                    if (selectedResult.getId()>0) {

                    } else {
                        selectedResult.setId(wrdao.findWhereUrlEquals(selectedResult.getUrl()).get(0).getId());
                    }
                } catch (Exception ex) {
                    
                }

                ArrayList<Rating> ratingList = (ArrayList<Rating>)  rdao.findWhereUserWebResourceEquals(currentUserID, selectedResult.getId());
                rateExplained = rtdao.findWhereIdEquals(rate).get(0).getName();
                if (ratingList.size()>0) {
                    Rating existingEvaluation = ratingList.get(0);
                    RatingPk existingEvPk = new RatingPk(existingEvaluation.getId());

                    existingEvaluation.setRatingTypeId(rate);

                    rdao.update(existingEvPk, existingEvaluation);

                    CommonUtils.recordUserAction(currentUserID, UserActivityTypeEnum.RATE, selectedResult.getId(), rateExplained);

                    FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Update Rating", "Your rating is updated: " + rateExplained);  

                    FacesContext.getCurrentInstance().addMessage(null, message); 


                } else {
                    Rating newEvaluation = new Rating();
                    newEvaluation.setUserId(currentUserID);
                    newEvaluation.setWebResourceId(selectedResult.getId());
                    newEvaluation.setRatingTypeId(rate);
                    rdao.insert(newEvaluation);

                    FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "New Rating", "Your rating is saved: " + rateExplained);  

                    FacesContext.getCurrentInstance().addMessage(null, message);  

                    CommonUtils.recordUserAction(currentUserID, UserActivityTypeEnum.RATE, selectedResult.getId(), rateExplained);
                }
                
                ArrayList<Rating> wrRatings = (ArrayList<Rating>) rdao.findWhereWebResourceIdEquals(selectedResult.getId());
                Double avRating = 0.0;
                for (int i=0; i<wrRatings.size(); i++) {
                    avRating += wrRatings.get(i).getRatingTypeId();
                }
                
                if (wrRatings.size()>0) {
                    avRating /= wrRatings.size();
                }
                
                selectedResult.setAverageRating(avRating);
                selectedResult.setAverageRatingInt(avRating.intValue());
                selectedResult.setRatingCount(wrRatings.size());
                wrdao.update(new WebResourcePk(selectedResult.getId()), selectedResult);
                
            } catch (RatingTypeDaoException ex) {

            } catch (RatingDaoException ex) {

            } catch (WebResourceDaoException ex) {
                
            }
            
        } else {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Warning", "You have to be logged in to rate");  

            FacesContext.getCurrentInstance().addMessage(null, message);
        }
    }  
      
    /**
     * On rate cancel event
     */
    public void onRateCancel() {  
        
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        RatingDao rdao = DaoFactory.createRatingDao();
        RatingTypeDao rtdao = DaoFactory.createRatingTypeDao();
        String errorText = "ERROR";
        String rateExplained = "";
        WebResourceDao wrdao = DaoFactory.createWebResourceDao();
        
        LoginBean loginBean = (LoginBean) context.getExternalContext().getSessionMap().get("loginBean");
        if (loginBean!=null && loginBean.isLoggedIn()) {
            int currentUserID = ((LoginBean) context.getExternalContext().getSessionMap().get("loginBean")).getUser().getId();

            try {
                
                try {
                    if (selectedResult.getId()>0) {

                    } else {
                        selectedResult.setId(wrdao.findWhereUrlEquals(selectedResult.getUrl()).get(0).getId());
                    }
                } catch (Exception ex) {
                    
                }
                
                ArrayList<Rating> ratingList = (ArrayList<Rating>)  rdao.findWhereUserWebResourceEquals(currentUserID, selectedResult.getId());

                if (ratingList.size()>0) {
                    Rating existingEvaluation = ratingList.get(0);
                    RatingPk existingEvPk = new RatingPk(existingEvaluation.getId());

                    rdao.delete(existingEvPk);
                    
                    
                    
                    ArrayList<Rating> wrRatings = (ArrayList<Rating>) rdao.findWhereWebResourceIdEquals(selectedResult.getId());
                    Double avRating = 0.0;
                    for (int i=0; i<wrRatings.size(); i++) {
                        avRating += wrRatings.get(i).getRatingTypeId();
                    }
                    
                    if (wrRatings.size()>0) {
                        avRating /= wrRatings.size();
                    }
                    
                    selectedResult.setAverageRating(avRating);
                    selectedResult.setAverageRatingInt(avRating.intValue());
                    selectedResult.setRatingCount(wrRatings.size());
                    wrdao.update(new WebResourcePk(selectedResult.getId()), selectedResult);
                    
                    FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Cancel Rating", "Your rating is cancelled");  

                    FacesContext.getCurrentInstance().addMessage(null, message);  
                } else {
                    FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Cancel Rating", "You didn't rate this before");  

                    FacesContext.getCurrentInstance().addMessage(null, message);  
                }

            } catch (WebResourceDaoException ex) {
                
            } catch (RatingDaoException ex) {

            }
            
        } else {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Warning", "You have to be logged in to change rate");  

            FacesContext.getCurrentInstance().addMessage(null, message);
        }
    }  
    
    /**
     * If the update is allowed
     * 
     * @param comment
     * @return 
     */
    public boolean canUpdate(Comment comment) {
        
        LoginBean loginBean = (LoginBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("loginBean");
        if (loginBean!= null && loginBean.isLoggedIn()) {
            
            if ((loginBean.getUser().getId() == comment.getUserId()) || (loginBean.isIsAdmin())) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * Remove comment
     * 
     * @param toBeRemovedComment 
     */
    public void removeComment(Comment toBeRemovedComment) {
        
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        CommentDao cdao = DaoFactory.createCommentDao();
        String errorText = "ERROR";
        
        LoginBean loginBean = (LoginBean) context.getExternalContext().getSessionMap().get("loginBean");
        if (loginBean!=null && loginBean.isLoggedIn()) {
            int currentUserID = ((LoginBean) context.getExternalContext().getSessionMap().get("loginBean")).getUser().getId();

            try {
                CommentPk commentPk = new CommentPk(toBeRemovedComment.getId());
                cdao.delete(commentPk);
                commentList.remove(toBeRemovedComment);
                
                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Remove Comment", "Your comment is removed");  
                FacesContext.getCurrentInstance().addMessage(null, message);  
            
            } catch (CommentDaoException ex) {

            }
            
        } else {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Warning", "You have to be logged in to delete comment");  
            FacesContext.getCurrentInstance().addMessage(null, message);
        }
        
    }
    
    /**
     * Add comment
     * 
     */
    public void addComment() {
        
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        RatingDao rdao = DaoFactory.createRatingDao();
        RatingTypeDao rtdao = DaoFactory.createRatingTypeDao();
        String errorText = "ERROR";
        String rateExplained = "";
        
        LoginBean loginBean = (LoginBean) context.getExternalContext().getSessionMap().get("loginBean");
        if (loginBean!=null && loginBean.isLoggedIn()) {
            int currentUserID = ((LoginBean) context.getExternalContext().getSessionMap().get("loginBean")).getUser().getId();
            
            CommentDao cdao = DaoFactory.createCommentDao();
            Comment comment = new Comment();
            comment.setLikeCount(0);
            comment.setUserId(currentUserID);
            comment.setUserText(loginBean.getUser().getName());
            comment.setWebResourceId(selectedResult.getId());
            comment.setTime(new Date());
            comment.setText(newCommentText);
            cdao.insert(comment);
        
            commentList.add(comment);
            CommonUtils.recordUserAction(currentUserID, UserActivityTypeEnum.COMMENT, selectedResult.getId(), newCommentText);
            
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Update Rating", "Comment added");  
            FacesContext.getCurrentInstance().addMessage(null, message); 
            
        } else {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Warning", "You have to be logged in to comment");  

            FacesContext.getCurrentInstance().addMessage(null, message);
        }
        
    }
    
    /**
     * On edit comment event
     * 
     * @param event 
     */
    public void onEditCommentRow(RowEditEvent event) {
        log.debug("[WebResourceBean.onEditCommentRow] started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        try {
            Comment comment = (Comment)event.getObject();
            CommentDao cdao = DaoFactory.createCommentDao();
            cdao.update(new CommentPk(comment.getId()), comment);
            
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Comment Updated"));
            
        } catch (Exception ex) {
            log.error("[WebResourceBean.onEditCommentRow] - exception message: " + ex.getMessage());
            text = "General error with DB";
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, text));
        }
    }
    
    /**
     * Like comment
     * 
     * @param comment 
     */
    public void likeComment(Comment comment) {
        
        log.debug("[WebResourceBean.likeComment] started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        try {
            
            int currentUserID = ((LoginBean) context.getExternalContext().getSessionMap().get("loginBean")).getUser().getId();
            CommentLikeDao cldao = DaoFactory.createCommentLikeDao();
            CommentLike cl = new CommentLike();
            cl.setCommentId(comment.getId());
            cl.setUserId(currentUserID);
            cldao.insert(cl);
            
            CommonUtils.recordUserAction(currentUserID, UserActivityTypeEnum.LIKE, selectedResult.getId(), comment.getText());
            
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Comment liked"));
            
        } catch (Exception ex) {
            log.error("[WebResourceBean.likeComment] - exception message: " + ex.getMessage());
            text = "General error with DB";
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, text));
        }
        
    }

    /**
     * Unlike comment
     * 
     * @param comment 
     */
    public void unlikeComment(Comment comment) {
        
        log.debug("[WebResourceBean.likeComment] started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        try {
            
            int currentUserID = ((LoginBean) context.getExternalContext().getSessionMap().get("loginBean")).getUser().getId();
            CommentLikeDao cldao = DaoFactory.createCommentLikeDao();
            ArrayList<CommentLike> commentLikeList = (ArrayList<CommentLike>)cldao.findWhereCommentIdAndUserIdEquals(currentUserID, comment.getId());
            if (commentLikeList.size()>0) {
                CommentLikePk clpk = new CommentLikePk();
                clpk.setId(commentLikeList.get(0).getId());
                cldao.delete(clpk);
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Comment unliked"));
            } else {
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "No like exists"));
            }
             
        } catch (Exception ex) {
            log.error("[WebResourceBean.likeComment] - exception message: " + ex.getMessage());
            text = "General error with DB";
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, text));
        }
        
    }
    
    /**
     * Check if can like comment
     * 
     * @param comment
     * @return 
     */
    public boolean canLikeComment(Comment comment) {
        LoginBean loginBean = (LoginBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("loginBean");
        if (loginBean!= null && loginBean.isLoggedIn()) {
            int  currentUserID = loginBean.getUser().getId();
            
            CommentLikeDao cldao = DaoFactory.createCommentLikeDao();
            try {
                if (cldao.getUserLikeCountForComment(currentUserID, comment.getId()) > 0) {
                    return false;
                }
            } catch (CommentLikeDaoException ex) {
                return true;
            }
            
        }
        return true;
    }
    
    /**
     * Get comment list
     * 
     * @return 
     */
    public ArrayList<Comment> getCommentList() {
        
        CommentDao cdao = DaoFactory.createCommentDao();
        UserDao udao = DaoFactory.createUserDao();
        CommentLikeDao cldao = DaoFactory.createCommentLikeDao();
                    
        if (selectedResult != null) {
            try {
                if (selectedResult.getId() >0) {

                    commentList = (ArrayList<Comment>) cdao.findByWebResource(selectedResult.getId());
                    for (int i=0; i<commentList.size(); i++) {
                        commentList.get(i).setUserText(udao.findWhereIdEquals(commentList.get(i).getUserId()).get(0).getName());
                        commentList.get(i).setLikeCount(cldao.getLikeCount(commentList.get(i).getId()));
                    }
                    
                } else {

                    WebResourceDao wrDao = DaoFactory.createWebResourceDao();
                    try {
                        WebResource wr = wrDao.findWhereUrlEquals(selectedResult.getUrl()).get(0);
                        selectedResult.setId(wr.getId());
                        commentList = (ArrayList<Comment>) cdao.findByWebResource(selectedResult.getId());
                        for (int i=0; i<commentList.size(); i++) {
                            commentList.get(i).setUserText(udao.findWhereIdEquals(commentList.get(i).getUserId()).get(0).getName());
                            commentList.get(i).setLikeCount(cldao.getLikeCount(commentList.get(i).getId()));
                        }
                    } catch (Exception ex) {
                        
                    }
                }
                
            } catch (CommentDaoException ex) {
                
            } catch (CommentLikeDaoException ex) {
                
            } catch (UserDaoException ex) {
                
            }
        }
        return commentList;
    }
    
    /**
     * Get if the user favorited the course
     * 
     * @param id
     * @return 
     */
    private boolean getIfUserFavoritedCourse(int id) {
        FacesContext context = FacesContext.getCurrentInstance();
        LoginBean loginBean = (LoginBean) context.getExternalContext().getSessionMap().get("loginBean");
        UserFavoriteDao ufDao = DaoFactory.createUserFavoriteDao();
        boolean result = false;
        if (loginBean!=null && loginBean.isLoggedIn()) {
            int currentUserID = ((LoginBean) context.getExternalContext().getSessionMap().get("loginBean")).getUser().getId();
            try {
                if (ufDao.findWhereUserIdAndWebResourceIdEquals(currentUserID, id).size()>0) {
                    result = true;
                }
            } catch (Exception ex) {
                
            }
            
        }
        return result;
    }
    
    
    /**
     * Retrieve lessons from DB
     * 
     * @param searchText
     * @return 
     */
    private ArrayList<Lessons> retrieveLessons(String searchText) {
        log.debug("[WebResourceBean.retrieveLessons] started");
        String text;
        String errorText = "ERROR";
        try {
            LessonsDao lDao = DaoFactory.createLessonsDao();
            WebResourceDao wDao  =DaoFactory.createWebResourceDao();
            lessons =  (ArrayList<Lessons>) lDao.selectLessons(searchText);
            for (int i=0;i<lessons.size(); i++) {
                Lessons l = lessons.get(i);
                if (l.getUrl() == null || l.getUrl().isEmpty()) {
                    lessons.get(i).setUrl(wDao.findWhereIdEquals(l.getWebresourceId()).get(0).getUrl());
                }
            }
            if (searchResults != null && !searchResults.isEmpty()) {
                for (int i=0; i<searchResults.size(); i++) {
                    if (searchResults.get(i).getLessons() != null && !searchResults.get(i).getLessons().isEmpty()) {
                        lessons.addAll(searchResults.get(i).getLessons());
                    }
                }
            }
            
        } catch (LessonsDaoException ex) {
           
        } catch (WebResourceDaoException ex) {
           
        }
        return lessons;
    }
    
    /*----Getter Setters---- */

    

    public void setCommentList(ArrayList<Comment> commentList) {
        this.commentList = commentList;
    }
    
    public ArrayList<WebResource> getLastCourses() {
        log.debug("[WebResourceBean.getLastCourses] - started");
        return lastCourses;
    }

    public ArrayList<WebResource> getLastInstitutions() {
        log.debug("[WebResourceBean.getLastCourses] - started");
        return lastInstitutions;
    }
    
    public ArrayList<WebResource> getTopCourses() {
        log.debug("[WebResourceBean.getLastCourses] - started");
        return topCourses;
    }

    public ArrayList<WebResource> getTopInstitutions() {
        log.debug("[WebResourceBean.getTopInstitutions] - started");
        return topInstitutions;
    }

    public ArrayList<WebResource> getTopInstructors() {
        log.debug("[WebResourceBean.getTopInstructors] - started");
        return topInstructors;
    }
    
    public boolean isSearchFinished() {
        return searchFinished;
    }

    public void setSearchFinished(boolean searchFinished) {
        this.searchFinished = searchFinished;
    }

    public String getSearchText() {
        return searchText;
    }

    public void setSearchText(String searchText) {
        this.searchText = searchText;
    }

    public ArrayList<WebResource> getSearchResults() {
        return searchResults;
    }

    public void setSearchResults(ArrayList<WebResource> searchResults) {
        this.searchResults = searchResults;
    }

    public DashboardModel getTopsDashboard() {
        topsDashboard = new DefaultDashboardModel();
        DashboardColumn column1 = new DefaultDashboardColumn();

        column1.addWidget("topCourses");
        column1.addWidget("topInstructors");
        column1.addWidget("topInstitutions");

        topsDashboard.addColumn(column1);

        return topsDashboard;
    }

    public void setTopsDashboard(DashboardModel topsDashboard) {
        this.topsDashboard = topsDashboard;
    }

    public DashboardModel getRightCoursesPanel() {
        rightCoursesPanel = new DefaultDashboardModel();
        DashboardColumn column1 = new DefaultDashboardColumn();

        column1.addWidget("recommendedCourses");
        column1.addWidget("newCoursesSummary");
        column1.addWidget("trendingCourses");
        rightCoursesPanel.addColumn(column1);

        return rightCoursesPanel;
    }

    public void setRightCoursesPanel(DashboardModel rightCoursesPanel) {
        this.rightCoursesPanel = rightCoursesPanel;
    }

    public DashboardModel getRightAdminPanel() {
        rightAdminPanel = new DefaultDashboardModel();
        DashboardColumn column1 = new DefaultDashboardColumn();

        column1.addWidget("newUsers");
        column1.addWidget("newVideos");
        column1.addWidget("newCourses");
        rightAdminPanel.addColumn(column1);

        return rightAdminPanel;
    }

    public void setRightAdminPanel(DashboardModel rightAdminPanel) {
        this.rightAdminPanel = rightAdminPanel;
    }

    public WebResource getSelectedResult() {
        if (selectedResult == null) {
            selectedResult = new WebResource();
        }
        return selectedResult;
    }

    public void setSelectedResult(WebResource selectedResult) {
        
        FacesContext context = FacesContext.getCurrentInstance();
        LoginBean loginBean = (LoginBean) context.getExternalContext().getSessionMap().get("loginBean");
        if (loginBean!=null && loginBean.isLoggedIn()) {
            int currentUserID = ((LoginBean) context.getExternalContext().getSessionMap().get("loginBean")).getUser().getId();
            CommonUtils.recordUserAction(currentUserID, UserActivityTypeEnum.VIEW, selectedResult.getId(), null);
        }
        
        this.selectedResult = selectedResult;
    }

    public Integer getRate() {
        return rate;
    }

    public void setRate(Integer rate) {
        this.rate = rate;
    }

    public Comment getToBeRemovedComment() {
        return toBeRemovedComment;
    }

    public void setToBeRemovedComment(Comment toBeRemovedComment) {
        this.toBeRemovedComment = toBeRemovedComment;
    }

    public String getNewCommentText() {
        return newCommentText;
    }

    public void setNewCommentText(String newCommentText) {
        this.newCommentText = newCommentText;
    }

    public ArrayList<WebResource> getTrendingCourses() {
        return trendingCourses;
    }

    public void setTrendingCourses(ArrayList<WebResource> trendingCourses) {
        this.trendingCourses = trendingCourses;
    }

    public String getTagSuggestion() {
        return tagSuggestion;
    }

    public void setTagSuggestion(String tagSuggestion) {
        this.tagSuggestion = tagSuggestion;
    }

    public ArrayList<Lessons> getLessonResults() {
        return lessonResults;
    }

    public void setLessonResults(ArrayList<Lessons> lessonResults) {
        this.lessonResults = lessonResults;
    }


    
    
    
}
